#include "udp_client.hpp"

using namespace std;

void usage(std::string proc)
{
    cout << "Usage:\n\t" << proc << " serverip serverport" << endl;
}

void *recever(void *args)
{
    int sock = *(static_cast<int *>(args));

    while (true)
    {
        char buffer[1024];
        struct sockaddr_in peer;
        socklen_t len = sizeof(peer);

        int n = recvfrom(sock, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&peer, &len);
        if (n > 0)
        {
            buffer[n] = '\0';
            cout << buffer << std::endl;
        }
    }
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        usage(argv[0]);
        return USAGR_ERR;
    }

    std::string serverip = argv[1];
    uint16_t serverport = atoi(argv[2]);

    int sock = socket(AF_INET, SOCK_DGRAM, 0);
    if (sock < 0)
    {
        std::cerr << "create socket error: " << strerror(errno) << std::endl;
        exit(SOCKET_ERR);
    }

    sockaddr_in server;
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    server.sin_addr.s_addr = inet_addr(serverip.c_str());

    pthread_t tid;
    pthread_create(&tid, nullptr, recever, &sock);

    while (true)
    {
        std::string message;
        cerr << "please Enter# ";
        getline(cin, message);

        sendto(sock, message.c_str(), message.size(), 0, (sockaddr *)&server, sizeof(server));
    }
    return 0;
}